package com.gx.auth.dao;

import com.gx.auth.common.BaseDAO;
import com.gx.auth.entity.Function;
import com.gx.auth.entity.RoleFunction;
import com.gx.auth.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Administrator on 2017/4/4.
 */
@Slf4j
public class RoleFunctionDAO extends BaseDAO {
    private class RoleFunctionMapper implements RowMapper {
        @Override
        public Object mapRow(ResultSet resultSet, int i) throws SQLException {
            RoleFunction roleFunction = new RoleFunction();
            roleFunction.setId(resultSet.getLong("id"));
            roleFunction.setRoleId(resultSet.getLong("role_id"));
            roleFunction.setFunctionId(resultSet.getLong("function_id"));
            roleFunction.setStatus(resultSet.getInt("status"));
            return roleFunction;
        }
    }


    /**
     * 根据id查找 角色功能对应关系
     *
     * @param id
     * @return
     */
    public RoleFunction findRoleFunctionById(Long id) {
        String sql = "select * from auth_user where id = ? ";
        try {
            return (RoleFunction) jdbcTemplate.queryForObject(sql, new Object[]{id}, new RoleFunctionMapper());
        } catch (Exception e) {
            log.error("查询getUser异常：" + e.getMessage(), e);
            return null;
        }
    }


    /**
     * 批量插入
     *
     * @param roleFunctions
     */
    public void insertRoleFunctions(Collection<RoleFunction> roleFunctions) {
        String sql = "insert  auth_rolefunction (role_id,function_id,status) values(?,?,?) ";
        List<Object[]> batchArgs = new ArrayList<>();
        roleFunctions.forEach(
                (rf) -> {
                    Object[] objs = new Object[3];
                    objs[1] = rf.getRoleId();
                    objs[2] = rf.getFunctionId();
                    objs[3] = rf.getStatus();
                    batchArgs.add(objs);
                });
        jdbcTemplate.batchUpdate(sql, batchArgs);
    }

    /**
     * 根据角色ID 查询角色对应关系集合
     * @param id
     * @return
     */
    public List<RoleFunction> findRoleFunctionByRoleId(Long id) {
        String sql = "SELECT *  from anth_role_function  where id = ?";
        return jdbcTemplate.query(sql, new Object[]{id}, new RoleFunctionMapper());
    }

    /**
     * 根据角色id删除对应关系
     * @param roleId
     * @return
     */
    public int deleteByRoleId(Long roleId) {
        String sql = "delete from auth_role_function where role_id = ? ";
        return jdbcTemplate.update(sql, roleId);

    }
}
